﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
using AutoMapper.Internal.Mappers;
using BW.WMS.BasicData_LC.Dto.Input;
using BW.WMS.BasicData_LC.Dto.OutPut;
using BW.WMS.CodeEnum;
using BW.WMS.LC.Dto.Input;
using BW.WMS.Model;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.ObjectMapping;
using Volo.Abp.Uow;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;
using Me_StCur = BW.WMS.Model.Me_StCur;
using Me_StSub = BW.WMS.Model.Me_StSub;

namespace BW.WMS
{
    public class StHdAppService : ApplicationService, IStHdAppService
    {
        private readonly IRepository<Me_StHd, Guid> _sthdRepository;
        private readonly IRepository<Dm_Code, Guid> _codeRepository;
        private readonly IRepository<Dm_Warehouser, Guid> _WarehouserRepository;
        private readonly IRepository<Dm_Librarylocation, Guid> _librarylocationRepository;
        private readonly IRepository<OrderFormModel, Guid> _orderFormRepository;
        private readonly IRepository<Me_StCur, Guid> stCurRepository;
        private readonly IRepository<Me_StSub, Guid> stSubRepository;
        private readonly IRepository<Dm_Item, Guid> _itemRepository;

        public StHdAppService(IRepository<Me_StHd, Guid> sthdRepository, IRepository<Dm_Code, Guid> codeRepository, IRepository<Dm_Warehouser, Guid> warehouserRepository, IRepository<Dm_Librarylocation, Guid> librarylocationRepository, IRepository<OrderFormModel, Guid> orderFormRepository, IRepository<Me_StCur, Guid> stCurRepository, IRepository<Me_StSub, Guid> stSubRepository, IRepository<Dm_Item, Guid> itemRepository)
        {
            _sthdRepository = sthdRepository;
            _codeRepository = codeRepository;
            _WarehouserRepository = warehouserRepository;
            _librarylocationRepository = librarylocationRepository;
            _orderFormRepository = orderFormRepository;
            this.stCurRepository = stCurRepository;
            this.stSubRepository = stSubRepository;
            _itemRepository = itemRepository;
        }

        /// <summary>
        /// 获取入库信息成功
        /// </summary>
        /// <param name="output"></param>
        /// <returns></returns>
        public async Task<ApiPaging<Me_StHdDto>> GetStHdDto(Me_StHdOutput output)
        {
            try
            {
                var sthd = await _sthdRepository.GetQueryableAsync();
                var code=await _codeRepository.GetQueryableAsync();
                var warehouse = await _WarehouserRepository.GetQueryableAsync();
                var Librarylocation=await _librarylocationRepository.GetQueryableAsync();
                var orderForm = await _orderFormRepository.GetQueryableAsync();
                var Item=await _itemRepository.GetQueryableAsync();
                var Me_StSub=await stSubRepository.GetQueryableAsync();

                var linq = from a in sthd
                           join b in code on a.Typeid equals b.Typeid
                           join c in warehouse on a.Warehouseid equals c.Warehouseid
                           join d in Librarylocation on a.Librarylocationid equals d.Librarylocationid
                           join e in orderForm on a.OrderFormId equals e.OrderFormId
                           join f in Me_StSub on a.Inoutid equals f.Inoutid
                           select new Me_StHdDto()
                           {
                               Inoutid = a.Inoutid,
                               Typeid = a.Typeid,
                               Typename=b.Typename,
                               Direction=a.Direction,
                               Warehouseid = a.Warehouseid,
                               Warehousename = c.Warehousename,
                               Librarylocationid = a.Librarylocationid,
                               Librarylocationname = d.Librarylocationname,
                               OrderFormId = a.OrderFormId,
                               Handempid=a.Handempid,
                               Memo=a.Memo,
                               Unitid=f.Unitid,
                               Prices=f.Prices,
                               Amount=f.Amount
                           };

                var count = linq.Count();
                var page = (int)Math.Ceiling(count / (double)output.pagesize);
                var list = linq.Skip((output.pageindex - 1) * output.pagesize).Take(output.pagesize).ToList();
                return new ApiPaging<Me_StHdDto>()
                {
                    Code = ApiEnum.Success,
                    Message = "获取入库信息成功",
                    TotalCount = count,
                    TotalPages = page,
                    PageData = list
                };
            }
            catch (Exception ex)
            {
                return new ApiPaging<Me_StHdDto>()
                {
                    Code = ApiEnum.Error,
                    Message = "查询失败：" + ex.Message,
                    TotalCount = 0,
                    TotalPages = 0,
                    PageData = new List<Me_StHdDto>()
                };
            }
        }
        /// <summary>
        /// 入库添加
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [UnitOfWork]
        public async Task<ApiResult<int>> AddMe_StHd(AddMe_StHdInput input)
        {
           var resutl = new ApiResult<int>();

           var a= ObjectMapper.Map<AddMe_StHdInput, Me_StHd>(input);
           await _sthdRepository.InsertAsync(a);
            
            var b = ObjectMapper.Map<AddMe_StHdInput, Me_StSub>(input);
            b.Inoutid = a.Inoutid;
       
            await stSubRepository.InsertAsync(b);

            
            var c = ObjectMapper.Map<AddMe_StHdInput,Me_StCur >(input);
            c.Warehouseid = a.Warehouseid;
            c.Librarylocationid = a.Librarylocationid;
            b.Itemid=c.Itemid;
            b.Quantity = c.Quantity;
            b.Invaliddate=c.Invaliddate;
            await stCurRepository.InsertAsync(c);
            
            
            resutl.Code = ApiEnum.Success;
            resutl.Message = "入库添加成功";
            resutl.Data = 1;
            return resutl;

        }
       

     
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> DelStHd(Guid id)
        {
            var result = new ApiResult<int>();
            
            try
            {
                // 检查记录是否存在
                var entity = await _sthdRepository.GetAsync(id);
                if (entity == null)
                {
                    result.Code = ApiEnum.Fail;
                    result.Message = "记录不存在";
                    result.Data = 0;
                    return result;
                }

                // 执行删除操作
                await _sthdRepository.DeleteAsync(entity);
                
                result.Code = ApiEnum.Success;
                result.Message = "删除成功";
                result.Data = 1;
            }
            catch (Exception ex)
            {
                result.Code = ApiEnum.Error;
                result.Message = "删除失败：" + ex.Message;
                result.Data = -1;
            }
            
            return result;
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [UnitOfWork]
        public async Task<ApiResult<int>> UpdateMe_StHd(AddMe_StHdInput input)
        {

            var resutl = new ApiResult<int>();

            var a = ObjectMapper.Map<AddMe_StHdInput, Me_StHd>(input);
            await _sthdRepository.UpdateAsync(a);

            var b = ObjectMapper.Map<AddMe_StHdInput, Me_StSub>(input);
            b.Inoutid = a.Inoutid;

            await stSubRepository.UpdateAsync(b);


            var c = ObjectMapper.Map<AddMe_StHdInput, Me_StCur>(input);
            c.Warehouseid = a.Warehouseid;
            c.Librarylocationid = a.Librarylocationid;
            b.Itemid = c.Itemid;
            b.Quantity = c.Quantity;
            b.Invaliddate = c.Invaliddate;
            await stCurRepository.UpdateAsync(c);


            resutl.Code = ApiEnum.Success;
            resutl.Message = "入库修改成功";
            resutl.Data = 1;
            return resutl;

        }

        public async Task<ApiResult<List<Dm_ItemDto>>> GetDm_Item()
        {
            var departmentsQuery = await _itemRepository.GetQueryableAsync();

            var departmentsList = departmentsQuery.ToList();


            var dtos = ObjectMapper.Map<List<Dm_Item>, List<Dm_ItemDto>>(departmentsList);

            return new ApiResult<List<Dm_ItemDto>> ()
            {
                Code = ApiEnum.Success,
                Message = "获取 商品信息下拉框列表成功",
                Data = dtos
            };
        }
    }
}
